/**
 * 
 */
package com.star.mina;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

import org.apache.mina.api.IoFuture;
import org.apache.mina.api.IoSession;
import org.apache.mina.transport.nio.NioTcpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName: MinaClient
 * @Description: TODO
 * @author starhq
 * @createtime 2014年12月6日 下午2:46:05
 * @email : jian.wang@shinsoft.net
 * @modify by TODO
 * @resaon
 * @edittime
 * @version 1.0
 * @copyright shinsoft
 */
@Component("client")
public class MinaClient {

	@Autowired
	private MyHandler myHandler;

	private IoSession session;

	private static final Logger LOGGER = LoggerFactory
			.getLogger(MinaClient.class);

	@PostConstruct
	public void connect() {
		LOGGER.debug("start to connect server");
		final NioTcpClient client = new NioTcpClient();
		client.setFilters();
		client.setIoHandler(myHandler);
		IoFuture<IoSession> future = client.connect(new InetSocketAddress(
				"localhost", 8999));
		try {
			session = future.get();
			LOGGER.debug("connect to server success");
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	public void send(byte[] b) {
		final ByteBuffer bf = ByteBuffer.allocate(9);
		bf.put(b);
		bf.flip();
		session.write(bf);
	}

}
